package main

import (
	"fmt"
	"net"
)

/**
用户
*/
type User struct {
	Name    string
	Addr    string
	Channel chan string
	conn    net.Conn
	server  *Server
}

/**
创建用户
*/
func NewUser(conn net.Conn, server *Server) *User {
	userAddr := conn.RemoteAddr().String()
	user := &User{Name: userAddr,
		Addr:    userAddr,
		Channel: make(chan string),
		conn:    conn,
		server:  server,
	}
	//监听要发送的消息的通道
	go user.ListenMsg()
	return user
}

/**
监听Channel中的消息
*/
func (user *User) ListenMsg() {
	//从Channel中读取
	for {
		msg := <-user.Channel
		user.conn.Write([]byte(msg + "\n"))
	}
}

/**
用户上线
*/
func (user *User) Online() {
	user.server.mapLock.Lock()
	user.server.OnlineMap[user.Name] = user
	user.server.mapLock.Unlock()
	//发送广播消息
	user.server.BroadCast(user, "已上线")
}

/**
用户下线
*/
func (user *User) Offline() {
	user.server.mapLock.Lock()
	delete(user.server.OnlineMap, user.Name)
	user.server.mapLock.Unlock()
	user.server.BroadCast(user, "下线")
}

/**
用户收到消息
*/
func (user *User) receiveMsg(msg string) {
	fmt.Println("收到消息:" + msg)
	//广播消息
	user.server.BroadCast(user, msg)
}
